# !/bin/bash

[ $# != "2" ] && echo "Usage: $0 dir/to/be/packed /output/to/" && exit 0

MV_PWD=$(cd $1 && pwd)
appended_dir="${MV_PWD##*/}"
cd $MV_PWD/..
temp_dir=$(mktemp -d)
appended_tar=$temp_dir/$appended_dir.tar
tar -cf $appended_tar $appended_dir
last_char=$(od -j$(($(wc -c $appended_tar | awk '{print $1}') - 1)) -c $appended_tar | head -n1 | awk '{print $2}')
file_name="$2/$appended_dir.sh"
target_md5=$(md5sum $appended_tar | awk '{print $1}')
skip_lines=$( [ "$last_char" = "\n" ] && echo 12 || echo 11 )

echo "# !/bin/bash" > $file_name
echo "[ \$# -gt \"1\" ] && echo \"Usage: \$0 <dest_dir>\" && exit 0" >> $file_name
echo "lines=\`wc -l \$0 | awk '{ print \$1 }'\`" >> $file_name
echo "lines=\`expr \$lines - $skip_lines\`" >> $file_name
echo "buff_file=\`tempfile\`" >> $file_name
echo "tail -n \$lines \$0 > \$buff_file " >> $file_name
echo "[ \"\$(md5sum \$buff_file | awk '{print \$1}')\" = \"$target_md5\" ] && (echo \"Verify OK\") || (echo \"$appended_dir verify failed, DO NOT edit this file, pls\"; rm \$buff_file ; exit 2)" >> $file_name
echo "[ -n \"\$1\" ] && buff_dir=\$1 || buff_dir=\`mktemp -d\` ; echo \"will use \$buff_dir to extract tar files\"" >> $file_name
echo "cd \$buff_dir && tar -xf \$buff_file -C . ; rm \$buff_file; cd $appended_dir" >> $file_name
echo "[ -f autorun.sh ] && bash ./autorun.sh" >> $file_name
echo "echo -e \"\\nDirectory <$appended_dir> extracted at \$buff_dir \\n\"" >> $file_name
echo "exit 0" >> $file_name

cat $appended_tar >> $file_name
chmod +x $file_name
echo "File created at $file_name"
rm -rf $temp_dir
